package com.yimi.yinhepda.views.load_module;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pda.ym.db.table.UnloadScanTable;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.LoadTaskEntity;
import com.yimi.yinhepda.entity.bean.KuaYueChildWaybillEntitiy;
import com.yimi.yinhepda.entity.bean.KuaYueTaskDetailEntity;
import com.yimi.yinhepda.entity.request.CancleScanLoad;
import com.yimi.yinhepda.entity.request.CancleScanLoadRequest;
import com.yimi.yinhepda.entity.response.LoadInfo;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.event.ScanResult;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.fenbo_ziti.FenBoZiTiActivity;
import com.yimi.yinhepda.views.kua_yue_spotGoods.KuaYueSpotGoodsActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 手动装车撤销界面
 *
 * @author 000432
 */
public class BackoutActivity extends LoadBaseActivity {
    /**
     * 条码窗口
     */
    EditText delChildWaybillText;
    /**
     * 撤销文字，撤销记录统计
     */
    private TextView tv_backOut, manualDelCount;

    /**
     * 撤销的扫描件
     */
    private ArrayList<DeleteEntity> deleteEntityLists = new ArrayList<>();
    private ListView deleteListView;
    private DeleteScanedAdapter adapter;
    /**
     * 手动添加
     */
    private int inputType = 2;
    private String task;
    private List<LoadInfo> loadDataEntityList;
    /**
     * 部门类型
     */
    private int deptType;
    /**
     * 撤销类型：1-分拨自提扫描撤销,2-同行卸车撤销
     */
    private int delType;
    /**
     * 自提部门code
     */
    private String ziTiDeptCode;

    @Override
    public void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("扫描失败！");
        } else {
            delChildWaybillText.setText(result);
            doScan(result, 1);
        }
    }

    public BackoutActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backout);
        initView();
        initData();
        //注册事件
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.del_childwaybill_ok:
                activityBackMethod();
                break;
            case R.id.manual_del_btn:
                if (TextUtils.isEmpty(delChildWaybillText.getText().toString().trim())) {
                    SoundVibratorManager.playSound(2);
                    showToast("请输入要撤销的运单");
                    return;
                }
                doScan(delChildWaybillText.getText().toString().trim(), 2);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //不执行父类点击事件
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        //继续执行父类其他点击事件
        return super.onKeyDown(keyCode, event);
    }

    private void activityBackMethod() {
        Bundle bundle = new Bundle();
        setResult(LoadScanActivity.BACK_OUT_RESULT, this.getIntent().putExtras(bundle));
        finish();
    }

    private void initData() {
        deptType = getIntent().getIntExtra("deptType", 0);
        task = getIntent().getStringExtra("task");
        operTypeCode = getIntent().getIntExtra("operTypeCode", 1);
        delType = getIntent().getIntExtra("delType", 0);
        ziTiDeptCode = getIntent().getStringExtra("ziTiDeptCode");
        loadDataEntityList = LoadScanActivity.loadInfos;
        adapter = new DeleteScanedAdapter(this, deleteEntityLists);
        deleteListView.setAdapter(adapter);

        if (delType == 2) {
            //同行卸车
            num.setVisibility(View.GONE);
        } else {
            num.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public String getPageName() {
        return "撤销";
    }

    public void initView() {
        ((TextView) findViewById(R.id.title)).setText("撤销");
        num = findViewById(R.id.num);

        delChildWaybillText = findViewById(R.id.load_delchildwaybill_ed);
        manualDelCount = findViewById(R.id.manaul_del_count);
        deleteListView = findViewById(R.id.del_chidlwaybill_listview);

        findViewById(R.id.del_childwaybill_ok).setOnClickListener(this);

        findViewById(R.id.manual_del_btn).setOnClickListener(this);
    }

    /**
     * 撤销时重构数据
     * inputtype 2为手动撤销
     */
    private void doScan(String result, int inputtype) {

        //判断是否是主单号
        boolean isMasterWaybillNo = StringUtils.isMasterWayBillNo(result);
        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !isMasterWaybillNo
                && !UcWaybillValidate.validate(result) && !StringUtils.isKuaYueWaybillNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!(" + result + ")");
            return;
        }

        if (delType == 1) {
            //分拨自提扫描撤销
            String delResult = mUnloadScanTableDao.deleteZiTiData(result, ziTiDeptCode, sharedPreferUtil.getValue(Common.USER_CODE));
            if (delResult == null) {
                //更新展示删除的运单
                showDeleteWaybill(result, delType);
            } else {
                showToast(delResult);
                SoundVibratorManager.playSound(2);
            }
            return;
        } else if (delType == 2) {
            //同行卸车撤销
            for (KuaYueTaskDetailEntity detail : KuaYueSpotGoodsActivity.Companion.getMDataList()) {
                for (KuaYueChildWaybillEntitiy child : detail.getChildNos()) {
                    if (child.getSubOutsideNo().equals(result) || child.getSubWaybillNo().equals(result)) {
                        if (child.getFlag() == 1) {
                            //删除本地扫描表数据
                            int i = mUnloadScanTableDao.deleteByWaybillNo(result);
                            if (i != -1) {
                                //更新展示删除的运单
                                showDeleteWaybill(result, delType);
                                //设置未扫描状态
                                child.setFlag(0);
                                //发送消息处理撤销结果
                                EventBus.getDefault().post(new ScanResult(result, 4, 4));
                            } else {
                                showToast("撤销失败！(" + result + ")");
                                SoundVibratorManager.playSound(2);
                            }
                        } else {
                            showToast("运单未扫描！(" + result + ")");
                            SoundVibratorManager.playSound(2);
                        }
                        return;
                    }
                }
            }
        } else {
            if (UcWaybillValidate.validate(result)) {
                //撤销优速快递的运单
                for (LoadInfo loadInfo : loadDataEntityList) {
                    if(result.startsWith(loadInfo.getWaybillNo())){
                        boolean hasFlag = false;
                        List<CancleScanLoad> records = new ArrayList();
                        CancleScanLoadRequest cancleScanLoadRequest = new CancleScanLoadRequest();
                        if (loadInfo.getChildList() != null) {
                            for (QueryLoadDetailChildBillcode item : loadInfo.getChildList()) {
                                if (item.getFlag() == 1) {
                                    hasFlag = true;
                                    CancleScanLoad cancleScanLoad =
                                            new CancleScanLoad(loadInfo.getWaybillNo(), item.getChildWaybillNo(), loadInfo.getPackageNo(), item.getStowageNo(), 11, inputtype,
                                                    deptType, 2, loadInfo.getStowageNo(),sharedPreferUtil.getValue(Common.USER_CODE),
                                                    sharedPreferUtil.getEmpName(), sharedPreferUtil.getDeptCode());
                                    records.add(cancleScanLoad);
                                }
                            }
                        }
                        if (hasFlag) {
                            cancleScanLoadRequest.setRecords(records);
                            cancelMasterBillcode(cancleScanLoadRequest, loadInfo, result);
                        } else {
                            SoundVibratorManager.playSound(2);
                            Toast.makeText(this, "主单号中没有扫描的子单号！", Toast.LENGTH_LONG).show();
                        }
                        return;
                    }
                }
            } else {
                //撤销子单号
                Iterator it = loadDataEntityList.iterator();
                while (it.hasNext()) {
                    final LoadInfo billDto = (LoadInfo) it.next();
                    //判断主单是否相等，减少循环次数
                    if (!result.startsWith(billDto.getWaybillNo())) {
                        continue;
                    }
                    if (billDto.getChildList() != null && billDto.getChildList().size() > 0) {
                        for (final QueryLoadDetailChildBillcode item : billDto.getChildList()) {
                            //查询单号是否扫描
                            if (item.getChildWaybillNo().equals(result)) {
                                if (item.getFlag() == 1) {
                                    /**撤销已扫描的运单*/
                                    cancelBillcode(result, inputtype, billDto, item);
                                } else {
                                    SoundVibratorManager.playSound(2);
                                    Toast.makeText(this, "运单号未扫描！(" + result + ")", Toast.LENGTH_LONG).show();
                                }
                                return;
                            }
                        }
                    }
                }
            }
        }

        //该条码不在配载单据内
        SoundVibratorManager.playSound(2);
        Toast.makeText(this, "该运单不在配载单据内！(" + result + ")", Toast.LENGTH_SHORT).show();
    }

    /**
     * 更新展示删除的运单
     *
     * @param result  扫描的运单号
     * @param delType 撤销类型：1-分拨自提扫描撤销,2-同行卸车撤销
     */
    private void showDeleteWaybill(String result, int delType) {
        //更新列表
        boolean isExist = false;
        for (DeleteEntity item : deleteEntityLists) {
            if (result.startsWith(item.getWaybill())) {
                item.setCancelwaybillsNum((Integer.parseInt(item.getCancelwaybillsNum()) + 1) + "");
                item.setScanedwaybillsNum((Integer.parseInt(item.getScanedwaybillsNum()) - 1) + "");
                isExist = true;
                break;
            }
        }
        if (!isExist) {
            DeleteEntity mDeleteEntity = new DeleteEntity();
            int scanCount = 0;
            if (delType == 1) {
                //统计分拨自提扫描件数
                for (LoadInfo item : FenBoZiTiActivity.Companion.getLoadInfos()) {
                    if (result.startsWith(item.getWaybillNo())) {
                        scanCount = item.getScanCount();
                        break;
                    }
                }
                mDeleteEntity.setWaybill(result.substring(0, 12));
            } else if (delType == 2) {
                //统计同行卸车扫描件数
                for (KuaYueTaskDetailEntity item : KuaYueSpotGoodsActivity.Companion.getMDataList()) {
                    if (result.startsWith(item.getWaybillNo())) {
                        scanCount = item.getScanCount();
                        break;
                    }
                }
                if (StringUtils.isKuaYueWaybillNo(result)) {
                    mDeleteEntity.setWaybill(result.substring(0, 11));
                } else {
                    mDeleteEntity.setWaybill(result.substring(0, 12));
                }
            }
            mDeleteEntity.setScanedwaybillsNum(String.format("%s", Math.max((scanCount - 1), 0)));
            mDeleteEntity.setCancelwaybillsNum("1");
            deleteEntityLists.add(mDeleteEntity);
        }
        adapter.notifyDataSetChanged();
        excCount();
        SoundVibratorManager.playSound(1);
    }

    /**
     * 撤销已扫描的主单号
     */
    private void cancelMasterBillcode(final CancleScanLoadRequest cancleScanLoadRequest, final LoadInfo loadInfo, final String result) {
        setScannerEnabled(false);
        showPgDlg("正在撤销扫描数据...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_CANCLE_LOAD)
                .setRequestObject(cancleScanLoadRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof NoDataResponse) {
                            int count = 0;
                            //设置未扫描
                            List<QueryLoadDetailChildBillcode> childBillcodes = loadInfo.getChildList();
                            for (QueryLoadDetailChildBillcode item : childBillcodes) {
                                if (item.getFlag() == 1) {
                                    item.setFlag(0);
                                    count++;
                                }
                            }
                            //更新列表
                            boolean isExist = false;
                            for (DeleteEntity item : deleteEntityLists) {
                                if (item.getWaybill().equals(loadInfo.getWaybillNo())) {
                                    item.setScanedwaybillsNum(loadInfo.getScanCount() + "");
                                    item.setCancelwaybillsNum((count + Integer.parseInt(item.getCancelwaybillsNum())) + "");
                                    isExist = true;
                                    break;
                                }
                            }
                            if (!isExist) {
                                DeleteEntity mDeleteEntity = new DeleteEntity();
                                mDeleteEntity.setWaybill(result);
                                mDeleteEntity.setScanedwaybillsNum(loadInfo.getScanCount() + "");
                                mDeleteEntity.setCancelwaybillsNum(count + "");
                                deleteEntityLists.add(mDeleteEntity);
                            }
                            adapter.notifyDataSetChanged();

                            //删除数据库
                            try {
                                List<CancleScanLoad> cancleScanLoads = cancleScanLoadRequest.getRecords();
                                for (CancleScanLoad cancleScanLoad : cancleScanLoads) {
                                    for (CarPlanTaskEntity entity : LoadScanActivity.carPlanTaskEntityList) {
                                        List<UnloadScanTable> list = mUnloadScanTableDao.getTaskData(entity.getTaskNo(), cancleScanLoad.getChildWaybillNo());
                                        mUnloadScanTableDao.delete(list);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            //计算撤销票件
                            excCount();

                            //开启扫描
                            setScannerEnabled(true);
                            dismissPgDlg();
                            SoundVibratorManager.playSound(1);
                        }
                    }
                });
    }

    /**
     * 撤销已扫描的子单号
     */
    private void cancelBillcode(String result, int inputtype, final LoadInfo billDto, final QueryLoadDetailChildBillcode item) {
        try {
            CancleScanLoadRequest mCancleScanLoadRequest = new CancleScanLoadRequest();
            List<CancleScanLoad> records = new ArrayList<CancleScanLoad>();
            CancleScanLoad mCancleScanLoad = new CancleScanLoad(billDto.getWaybillNo(), result, billDto.getPackageNo(),
                    item.getStowageNo() == null ? billDto.getStowageNo() : item.getStowageNo(), 11,
                    inputtype, deptType, UcWaybillValidate.validate(billDto.getWaybillNo()) ? 2 : 1,
                    billDto.getStowageNo(),sharedPreferUtil.getValue(Common.USER_CODE), sharedPreferUtil.getEmpName(), sharedPreferUtil.getDeptCode());
            records.add(mCancleScanLoad);
            mCancleScanLoadRequest.setRecords(records);

            setScannerEnabled(false);
            showPgDlg("正在撤销扫描数据...");

            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(NoDataResponse.class)
                    .setUrl(Constants.URL_CANCLE_LOAD)
                    .setRequestObject(mCancleScanLoadRequest)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            //开启扫描
                            setScannerEnabled(true);
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            showToast(msg);
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            if (obj instanceof NoDataResponse) {
                                //设置未扫描
                                item.setFlag(0);
                                //更新列表
                                boolean isExist = false;
                                for (DeleteEntity item : deleteEntityLists) {
                                    if (item.getWaybill().equals(billDto.getWaybillNo())) {
                                        item.setCancelwaybillsNum((Integer.parseInt(item.getCancelwaybillsNum().toString()) + 1) + "");
                                        item.setScanedwaybillsNum((Integer.parseInt(item.getScanedwaybillsNum().toString()) - 1) + "");
                                        isExist = true;
                                        break;
                                    }
                                }
                                if (!isExist) {
                                    DeleteEntity mDeleteEntity = new DeleteEntity();
                                    mDeleteEntity.setWaybill(billDto.getWaybillNo());
                                    mDeleteEntity.setScanedwaybillsNum(billDto.getScanCount() + "");
                                    mDeleteEntity.setCancelwaybillsNum("1");
                                    deleteEntityLists.add(mDeleteEntity);
                                }
                                adapter.notifyDataSetChanged();
                                //删除数据库
                                try {
                                    for (CarPlanTaskEntity entity : LoadScanActivity.carPlanTaskEntityList) {
                                        List<UnloadScanTable> list = mUnloadScanTableDao.getTaskData(entity.getTaskNo(), item.getChildWaybillNo());
                                        mUnloadScanTableDao.delete(list);
                                    }
                                    if (billDto.getType() == 1 && billDto.getGoodsPriority() != null && Integer.parseInt(billDto.getGoodsPriority()) == Common.GOODSP_RIORITY_CHUAN) {
                                        //删除最后一条串货运单
                                        loadDataEntityList.remove(billDto);
                                    }
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }

                                ////设置库存件数
                                //billDto.setPiecesNum(billDto.getPiecesNum() + 1);
                                //计算撤销票件
                                excCount();

                                //开启扫描
                                setScannerEnabled(true);
                                dismissPgDlg();
                                SoundVibratorManager.playSound(1);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算撤销的票件
     */
    private void excCount() {
        int count = 0;
        for (DeleteEntity item : deleteEntityLists) {
            count += Integer.parseInt(item.getCancelwaybillsNum());
        }
        if (delType == 2) {
            tv_backOut.setText("撤销件数：");
            manualDelCount.setText(String.format("%s", count));
        } else {
            manualDelCount.setText(String.format("%s/%s", deleteEntityLists.size(), count));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CountEvent countEvent) {
        num.setText(countEvent.getCount() + "");
    }
}

class DeleteScanedAdapter extends BaseAdapter {
    private Context context;
    private List<DeleteEntity> dataList;

    public DeleteScanedAdapter(Context context, List<DeleteEntity> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        DeleteWayBillHolder mHolder;
        if (convertView == null) {
            mHolder = new DeleteWayBillHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.activity_del_scaned_waybillitem, null);
            mHolder.waybillno = (TextView) convertView.findViewById(R.id.cancelwaybill);
            mHolder.scanedwaybillNum = (TextView) convertView.findViewById(R.id.scanedwaybillnum);
            mHolder.cancelwayBillNum = (TextView) convertView.findViewById(R.id.canceledwaybillnum);

            convertView.setTag(mHolder);
        } else {
            mHolder = (DeleteWayBillHolder) convertView.getTag();
        }
        mHolder.waybillno.setText(dataList.get(position).getWaybill());
        mHolder.scanedwaybillNum.setText(dataList.get(position).getScanedwaybillsNum());
        mHolder.cancelwayBillNum.setText(dataList.get(position).getCancelwaybillsNum());

        return convertView;
    }
}

class DeleteWayBillHolder {
    TextView waybillno;
    TextView scanedwaybillNum;
    TextView cancelwayBillNum;
}

class DeleteEntity {
    /**
     * 运单号
     */
    private String waybill;
    /**
     * 已扫数量
     */
    private String scanedwaybillsNum;
    /**
     * 撤销数量
     */
    private String cancelwaybillsNum;

    public String getWaybill() {
        return waybill;
    }

    public void setWaybill(String waybill) {
        this.waybill = waybill;
    }

    public String getScanedwaybillsNum() {
        return scanedwaybillsNum;
    }

    public void setScanedwaybillsNum(String scanedwaybillsNum) {
        this.scanedwaybillsNum = scanedwaybillsNum;
    }

    public String getCancelwaybillsNum() {
        return cancelwaybillsNum;
    }

    public void setCancelwaybillsNum(String cancelwaybillsNum) {
        this.cancelwaybillsNum = cancelwaybillsNum;
    }
}